import { getNewestBPL, getDrugs, eatConfirm , getNewestTime , getHeartRate , getAbnormalBPL } from '../../../../utils/api/personalOverview'
import userBaseInfoState from '../../../../stores/userBaseInfo'
import { validateNull } from '../../../../utils/util'

// pages/home/home-nav/personal-overview/personal-overview.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    user: {
      name: '张三',
      birthday: '1990-01-01',
      sex: '男性',
      date: '0000-00-00',
      recordDate: '0000-00-00',
      time: '00:00',
      SBP: 0,
      DBP: 0,
      HR: 0,
      currentLevel: '正常',
      riskLevel: <RiskLevelEntity>{
        normal: 1,
        low: 1,
        light: 2,
        middle: 1,
        high: 2,
        all: 7,
      },
    },
    userInfo: <PatientBaseEntity>{
      patientUid: '',
      wxUid: '',
    },
    entries: [
      { time: '08: 00', medicine: '阿莫西林', dosage: '2粒', taken: true, status: '已服用', pepId: 123 },
      { time: '12: 00', medicine: '阿莫西林', dosage: '2粒', taken: false, status: '未服用', pepId: 123 },
      { time: '18: 00', medicine: '阿莫西林', dosage: '2粒', taken: false, status: '未服用', pepId: 123 },
    ],
    showDrugStatus: false,
    active: 0,
    currentComponent: <string | null>'PersonalOverview',
  },



  /**
   * 组件的方法列表
   */
  methods: {
    getNewBPL(patientUid: string | number) {
      // console.log('获取到的id是', patientUid);
      getNewestBPL(patientUid).then((res: any) => {
        // console.log('基础血压心率请求成功', res);
        this.setData({
          'user.SBP': res.data['收缩压'],
          'user.DBP': res.data['舒张压'],
          'user.currentLevel': res.data['风险评估'],
        })
      }).catch((err: any) => {
        console.log('基础血压心率请求失败', err);
      })
    },

    getRecordTime(patientUid: string | number) {
      getNewestTime(patientUid).then((res: any) => {
        // console.log('最新的记录时间是', res);
        const backendTime = res.data.latestTime; // 例如 "2024-08-03 18:31:42"
        const [recordDate, timeWithSeconds] = backendTime.split('T');
        const [hours, minutes] = timeWithSeconds.split(':').slice(0, 2); // 只取小时和分钟
        const time = `${hours}:${minutes}`;
        this.setData({
          'user.recordDate': recordDate,
          'user.time': time,
        })
      }).catch((err: any) => {
        console.log('记录时间请求失败', err);
      })
    },

    getNewHR(patientUid: string | number) {
      getHeartRate(patientUid).then((res: any) => {
        // console.log('最新的心率是', res);
        this.setData({
          'user.HR': res.data['心率'],
        })
      }).catch((err: any) => {
        console.log('心率请求失败', err);
      })
    },

    getRiskLevel(patientUid: string | number) {
      getAbnormalBPL(patientUid).then((res: any) => {
        let all = res.data['重度'] + res.data['中度'] + res.data['轻度'] + res.data['正常高值'] + res.data['偏低'];
        this.setData({
          'user.riskLevel.high': res.data['重度'],
          'user.riskLevel.middle': res.data['中度'],
          'user.riskLevel.light': res.data['轻度'],
          'user.riskLevel.normal': res.data['正常高值'],
          'user.riskLevel.low': res.data['偏低'],
          'user.riskLevel.all': all,
        })
        let chart = this.selectComponent('#anormalyStatistics');
        chart.updateRealData(this.data.user.riskLevel);
      })
    },

    getDrugsToEat(patientUid: string | number) {
      console.log('获取到的id是', patientUid)
      getDrugs(patientUid).then((res: any) => {
        // console.log('用药管理请求成功', res);
        if (res.code === 0 && res.data.length !== 0) {
          const entries = res.data.map((drug: any) => ({
            time: drug.eatTime.slice(0, 5), // 提取时间（时:分）
            medicine: drug.drugName,
            dosage: `${drug.dose}${drug.unit}`, // 用药剂量和单位
            taken: drug.isEaten,
            status: drug.isEaten ? '已服用' : '未服用',
            pepId: drug.pepId,
          }));
          // 更新entries数据
          this.setData({
            entries: entries,
            showDrugStatus: true,
          });
          // console.log('数据已更新');
        }
        else {
          console.log('用药管理请求成功但没有数据', res);
          this.setData({
            showDrugStatus: false,
          })
        }
      }).catch((err: any) => {
        console.log('用药管理请求失败', err);
      })
    },
    getDate() {
      var nowDate = new Date();
      console.log('获取的日期是', nowDate);
      let temp = nowDate.getMonth() + 1;
      let month = ('0' + temp).slice(-2);
      temp = nowDate.getUTCDate();
      let date = ('0' + temp).slice(-2);
      console.log(month);
      this.setData({
        'user.date': nowDate.getFullYear() + '-' + month + '-' + date,
      })
      // console.log('现在的日期是', this.data.user.date);
    },

    updateUserInfo(userInfo: PatientBaseEntity) {
      this.setData({
        userInfo: userInfo,
      })
      if (validateNull(userInfo.patientUid)) {
        return;
      }
      this.getDrugsToEat(<string>userInfo.patientUid);
      this.getDate();
      this.getNewBPL(<string>userInfo.patientUid);
      this.getRecordTime(<string>userInfo.patientUid);
      this.getNewHR(<string>userInfo.patientUid);
      this.getRiskLevel(<string>userInfo.patientUid)
    },

    eatDrug(event: any) {
      const pepId = event.currentTarget.dataset.index;
      // console.log('服用药物', pepId);
      eatConfirm(pepId).then((res: any) => {
        // console.log('服用成功', res);
        this.updateUserInfo(this.data.userInfo);
        // console.log('更新页面成功');
      }).catch((err: any) => {
        console.log('服用失败', err);
      })
    },

  },

  /**
   * 组件的生命周期方法
   */
  lifetimes: {
    ready: function () {
      console.log('初始化组件personal-overview');
    },
    attached: function () {
      this.updateUserInfo(this.data.userInfo);
    }
  },

  pageLifetimes: {
    show: function () {
      this.updateUserInfo(this.data.userInfo);
    }
  }
})